import { resolve } from "path";
import { defineConfig } from "vite";
import VuePlugin from "@vitejs/plugin-vue";
import LegacyPlugin from "@vitejs/plugin-legacy";
import autoprefixer from "autoprefixer";

export default defineConfig(({ mode }) => {
    // js兼容性
    const jsplugin =
        mode == "production"
            ? LegacyPlugin({
                  targets: ["chrome < 60", "edge < 15"],
                  additionalLegacyPolyfills: ["regenerator-runtime/runtime"],
                  renderLegacyChunks: true
              })
            : [];

    // css兼容性
    const cssplugin =
        mode == "production"
            ? [
                  autoprefixer({
                      overrideBrowserslist: ["last 2 versions"],
                      grid: true,
                      flexbox: true
                  })
              ]
            : [];
    // 上线替换
    const replugin = mode == "production" ? [] : [];
    return {
        root: "./src/",
        base: "./",
        publicDir: "./src/assets/",
        plugins: [...replugin, VuePlugin(), ...jsplugin],
        server: {
            open: true,
            port: 3000
        },
        resolve: {
            extensions: [".js", ".vue", ".scss"],
            alias: {
                "@": resolve(__dirname, "./src")
            }
        },
        css: {
            devSourcemap: true,
            postcss: {
                plugins: cssplugin
            }
        },
        build: {
            outDir: resolve(__dirname, "./build"),
            emptyOutDir: true,
            sourcemap: true,
            rollupOptions: {
                output: {
                    chunkFileNames: "js/[name].js",
                    entryFileNames: "js/[name]-[hash].js",
                    assetFileNames: (asset) => {
                        if (asset.name.includes(".css")) {
                            return "style/[name]-[hash].css";
                        } else {
                            return "assets/[name].[ext]";
                        }
                    },
                    manualChunks: {
                        "vue-vendor": ["vue", "vue-router"]
                    }
                }
            }
        }
    };
});
